define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/dialog",
    "UtilDir/combotree",
    "UtilDir/searchBlock",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, Dialog, Combotree, SearchBlock, fwsjcj) {

    var sysPath = getServer() + "/static/app/fwsjcj";

    var allotTaskFormHtml = sysPath + "/sifttaskmanage/views/allottaskForm.html";
    var TaskFormHtml = sysPath + "/sifttaskmanage/views/taskForm.html";
    var TaskFormHtmlReadOnly = sysPath + "/sifttaskmanage/views/taskFormReadOnly.html";
    var createTaskFormHtml = sysPath + "/sifttaskmanage/views/taskSetForm.html";
    var getDivisionController = function () {
        return getServer() + "/platform/org/divisions/";
    };
    /**
     * 页面初始化
     */
    var init = function () {
        initSearchBlock();
        queryBtnBind();
        createTaskGrid();
        initProvAndCityAndArea();
        //浏览器窗口大小变化后，表格宽度自适应
        $(window).resize(function () {
            createTaskGrid();
        });
    };
    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
    };
    var queryBtnBind = function () {
        $("#btnSearch").click(function () {
            createTaskGrid();
        });
        $("#btnReset").click(function () {
            $("#status").val("");
            $("#taskName").val("");
            $("#groupLeaderSearch").val("");
            resetProvAndCityAndArea();
        });
    };
    $("#tasklistlab").on('shown.bs.tab', function (e) {
        createTaskGrid();
    });
    $("#taskMaplab").on('shown.bs.tab', function (e) {
        //fwsjcj.fwsjcjInitAll();
    });
    $("#replayMaplab").on('shown.bs.tab', function (e) {
        replayInitAll();
    });
    var createTaskGrid = function () {
        var division;
        var city;
        city=$("#belongtoCity").val();
        division=$("#belongtoProvince").val()
        if(city!=null && city!="北京市" && city!="天津市" && city!="上海市" && city!="重庆市"){
            division+=city
        }else{
            division+=""
        }
        $("#taskGrid").datagrid({
            url: getServer() + "/fw/task/page/1",
            method: "GET",
            nowrap: false,
            columns: [[
                {field: "ck", checkbox: true},
                {field: 'taskNum', title: '任务编号', width: '15%', align: 'center'},
                {
                    field: 'taskName', title: '任务名称', width: '19.75%', align: 'center',
                    formatter: function (value, rowData, rowIndex) {
                        return '<a href="#" onclick="_view(\'' + rowData.taskId + '\',\'' + rowData.groupId + '\',\'' + rowData.taskName + '\',\'' + rowData.status + '\');"> ' + rowData.taskName + ' </a> '

                    }
                },
                {field: 'division', title: '任务地区', width: '13%', align: 'center'},
                {field: 'taskManager', title: '任务管理员', width: '10%', align: 'center'},
                {field: 'groupName', title: '承担小组', width: '15%', align: 'center'},
                {field: 'groupLeader', title: '组长', width: '10%', align: 'center'},
                {field: 'groupLeaderMobile', title: '手机号码', width: '10%', align: 'center'},
                {
                    field: 'status', title: '任务状态', width: '10%', align: 'center',
                    formatter: function (value, rowData, rowIndex) {
                        if (value == '0') {
                            return '未分配';
                        } else if (value == '1') {
                            return '进行中';
                        } else if (value == '2') {
                            return '已完成';
                        }
                    }
                },
//              {field:'operation',title:'操作',width:'14.8%',align:'center',
//              	formatter: function (value, rowData, rowIndex) {
//                      return '<a onclick="_complete(\'' + rowData.taskId+ '\')">完成</a>&nbsp;&nbsp;&nbsp;&nbsp;<a onclick="_uncheck(\'' + rowData.taskId+ '\')">分配</a >';                        		
//                  }
//              }
            ]],
            toolbar: [{
                iconCls: 'fa fa-plus-circle',
                text: "创建任务",
                handler: function () {
                    createTask()
                }
            }, {
                iconCls: 'fa fa-share-square-o',
                text: "分配",
                handler: function () {
                    allotTask()
                }
            }, {
                iconCls: 'fa fa-check-square-o',
                text: "完成",
                handler: function () {
                    completeTask()
                }
            }, {
                iconCls: 'fa fa-trash-o',
                text: "删除",
                handler: function () {
                    deleteTask()
                }
            }],
            queryParams: {
                status: $("#status").val(),
                taskName: $("#taskName").val(),
                groupLeader: $("#groupLeaderSearch").val(),
                division: division
            },
            pagination: true,
            pageSize: 10
        });
    };


    // 创建任务，字段校验
    var createformValidator = function () {
        $("#taskSetForm").validate({
            rules: {
                taskNum: {
                    required: true,
                    maxlength: 100
                },
                taskName: {
                    required: true,
                    maxlength: 100
                },
                division: {
                    required: true,
                    maxlength: 100
                }
            },
            messages: {
                taskNum: {
                    required: "任务编号不允许为空!",
                    maxlength: "任务编号长度不可以超过100"
                },
                taskName: {
                    required: "任务名称不允许为空!",
                    maxlength: "任务名称长度不可以超过100"
                },
                division: {
                    required: "任务地区不允许为空!",
                    maxlength: "任务地区长度不可以超过100"
                }
            }
        });
    };
    // 任务小组校验
    var allotformValidator = function () {
        $("#allotTaskForm").validate({
            rules: {
                taskGroup: {
                    required: true,
                    maxlength: 100
                }
            },
            messages: {
                taskGroup: {
                    required: "任务小组不允许为空!",
                    maxlength: "任务小组长度不可以超过100"
                }
            }
        });
    };

    var getTask = function (id) {
        $.ajax({
            url: getServer() + "/fw/task/" + id,
            type: "get",
            success: function (data) {
                Tool.deserialize("taskForm", data);
            }
        });
    };

    // 创建任务
    var createTask = function () {
        var slidebar = Util.slidebar({
            url: createTaskFormHtml,
            width: "800px",
            cache: false,
            close: true,
            afterOpen: function () {
                createGroupGrid();
            },
            afterLoad: function () {
                getTaskNum();
                initdivision();
                createformValidator();
                $("#saveBtn").on("click", function () {
                    if ($("#taskSetForm").valid()) {
//						var data = Tool.serialize("taskSetForm");
                        var data = {
                            taskId: $("#taskId").val(),
                            taskNum: $("#taskNum").val(),
                            taskName: $("#taskNameForm").val(),
                            taskType: $("#taskTypeForm").val(),
                            groupName: $("#taskGroup").val(),
                            division: $("#divisionId").val(),
                            groupId: $("#groupId").val(),
                            groupLeaderId: $("#groupLeaderId").val(),
                            groupLeader: $("#groupLeader").val(),
                            mapInfo: $("#taskArea").val(),
                        }
                        debugger;
                        if($("#division").val() == "中华人民共和国"){
						   Util.alert("请选择所属详细地区（除中华人民共和国）");
						    return;
                        }
                        $.ajax({
                            url: getServer() + "/fw/task/save",
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "post",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createTaskGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    var getTaskNum = function () {
        $.ajax({
            url: getServer() + "/fw/task/taskCode",
            type: "get",
            success: function (data) {
                debugger;
                $("#taskNum").val(data);
            }
        });
    };
    var allotTask = function () {
        var rows = $("#taskGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0 || rows.length > 1) {
            Util.alert("请选择一行数据!");
            return;
        } else if (rows[0].status == '2') {
            Util.alert("任务状态为已完成的不能再分配小组!");
            return;
        }
        var slidebar = Util.slidebar({
            url: allotTaskFormHtml,
            width: "800px",
            cache: false,
            close: true,
            afterOpen: function () {
                createGroupGrid(rows);
            },
            afterLoad: function () {
                allotformValidator();
                Tool.deserialize("allotTaskForm", rows[0]);
                $("#saveBtn").on("click", function () {
                    if ($("#allotTaskForm").valid()) {
//						var data = Tool.serialize("allotTaskForm");
                        var data = {
                            taskId: $("#taskId").val(),
                            taskName: $("#taskNameForm").val(),
                            taskType: $("#taskType").val(),
                            groupName: $("#taskGroup").val(),
                            groupId: $("#groupId").val(),
                            groupLeaderId: $("#groupLeaderId").val(),
                            groupLeader: $("#groupLeader").val(),
                        }
                        debugger;
                        $.ajax({
                            url: getServer() + "/fw/task/update",
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "post",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createTaskGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    var completeTask = function () {
        var rows = $("#taskGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        } else if (rows[0].status != '1') {
            Util.alert("只有任务状态为进行中的才能完成!");
            return;
        } else if (rows.length >= 1) {
            for (let i = 0; i < rows.length; i++) {
                if (rows[i].status != '1') {
                    Util.alert("只有任务状态为进行中的才能完成!");
                    return;
                }
            }
        }
        Util.confirm("是否要完成选中的任务?", function () {
            var ids = "";
            $.each(rows, function (i, row) {
                ids += row.taskId + ",";
            });
            ids = ids.substr(0, ids.length - 1);
            $.ajax({
                url: getServer() + "/fw/task/2/complete/" + ids,
                type: "post",
                success: function (data) {
                    createTaskGrid();
                }
            });
        }, function () {
            return;
        });
    };

    // 创建小组列表
    var createGroupGrid = function (rows) {
        debugger;
        $("#groupGrid").datagrid({
            url: getServer() + "/fw/group/page?groupType=1",
            method: "get",
            fitColumns: true,
            autoRowHeight: false,
            nowrap: false,
            columns: [[
                {
                    field: 'groupName',
                    title: '小组名称',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'groupLeader',
                    title: '小组组长',
                    width: '15%',
                    align: 'center'
                },
                {
                    field: 'groupMember',
                    title: '小组成员',
                    width: '27.7%',
                    align: 'center'
                },
                {
                    field: 'address',
                    title: '小组地区',
                    width: '25%',
                    align: 'center'
                },
                {
                    field: 'operation', title: '操作', width: '15%', align: 'center',
                    formatter: function (value, rowData, rowIndex) {
                        return '<a onclick="_allot(\'' + rowData.groupName + '\',\'' + rowData.id + '\',\'' + rowData.groupLeaderId + '\',\'' + rowData.groupLeader + '\')">分配</a >';
                    }
                }
            ]],
//          data: [{
//                  groupName: "小组一",
//                  taskType: "普查任务",
//                  groupMembers: "张一",
//                  groupLeader: "李一",
//                  groupRegion: "北京市"
//              }],
            pagination: true,
            pageSize: 10
        });
    };
    window._allot = function (groupName, groupId, groupLeaderId, groupLeader) {
        debugger;
        $("#taskGroup").val(groupName);
        $("#groupId").val(groupId);
        $("#groupLeaderId").val(groupLeaderId);
        $("#groupLeader").val(groupLeader);
    }

    // 查看任务详情
    window._view = function (taskId, groupId, taskName, status) {
        debugger;
        var taskFormHtml = '';
        if (status == "0") {
            taskFormHtml = TaskFormHtml;
        } else {
            taskFormHtml = TaskFormHtmlReadOnly;
        }
        var slidebar = Util.slidebar({
            url: taskFormHtml,
            width: "580px",
            cache: false,
            close: true,
            afterLoad: function () {
                getTask(taskId);
                //查看队员列表
                $("#viewteamBtn").bind("click", function () {
                    var buttons = [];
                    buttons.push({
                        name: '确定',
                        callback: function () {
                            //点击确定
                            dialog.hide();
                        }
                    });
                    var dialog = Dialog({
                        id: "viewTeamDialog",
                        cache: false,
                        title: '队员情况', //dialog标题
                        width: "1000px",
                        height: "550px",
                        body: '<div id="TeamGrid"></div>',
                        buttons: buttons,
                        afterOpen: function () {
                            $("#TeamGrid").datagrid({
                                url: getServer() + "/fw/group/" + groupId,
                                method: "GET",
                                height: "515px",
                                fitColumns: true,
                                nowrap: false,
                                autoRowHeight: false,
                                singleSelect: true,
                                columns: [[
                                    {field: 'relName', title: '姓名', width: '18%', align: 'center'},
                                    {field: 'idNumber', title: '身份证号', width: '28%', align: 'center'},
                                    {field: 'mobilePhone', title: '手机号', width: '23%', align: 'center'},
                                    {field: 'groupZW', title: '队内职务', width: '15%', align: 'center'},
                                    {field: 'formNum', title: '完成表单数量', width: '18%', align: 'center'},
                                    /*{field: 'operation', title: '操作', width: '17%', align: 'center',
                                        formatter: function (value, rowData, rowIndex) {
                                        debugger;
                                            return '<a onclick="_viewTrajectory(\'' + rowData.userId+ '\',\'' + taskId+ '\',\'' +taskName+ '\',\'' +rowData.relName+ '\')">查看队员轨迹</a >';
                                        }
                                    },*/
                                ]],

                                pagination: false,
                                pageSize: 10
                            });
                        }
                    });
                    dialog.show();
                    window._viewTrajectory = function (userId, taskId, taskName, userName) {
                        debugger;
                        dialog.hide();
                        slidebar.close();
                        $('#myTab a[href="#replayMap"]').tab('show');
                        //replayInitAll();
                        startReplayData(userId, taskId, taskName, userName);
                    }
                });
            }
        });
    };
    var deleteTask = function () {
        var rows = $("#taskGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        } else if (rows[0].status == '2') {
            Util.alert("任务状态为已完成的不能删除!");
            return;
        } else if (rows.length >= 1) {
            for (let i = 0; i < rows.length; i++) {
                if (rows[i].status == '2') {
                    Util.alert("任务状态为已完成的不能删除!");
                    return;
                }
            }
        }

        Util.confirm("删除任务，该任务下关联的采集数据系统自动删除，是否删除任务?", function () {
            var ids = "";
            $.each(rows, function (i, row) {
                ids += (row.taskId+"_"+row.taskType) + ",";
            });
            ids = ids.substr(0, ids.length - 1);
            $.ajax({
                url: getServer() + "/fw/task/" + ids,
                type: "post",
                success: function (data) {
                    createTaskGrid();
                }
            });
        }, function () {
            return;
        });

    };
    var initdivision = function () {
        var combotree = Combotree({
            // combo组件相关配置
            combo: {
                //要渲染的input的id
                id: "division",
                //下拉框的类型：单选or多选
                multi: false,
                key: {
                    idKey: "divisionId",
                    textKey: "divisionName"
                },
                //          placeholder: "请选择……",
                event: {
                    onShowPanel: function () {
                        console.log("show");
                    },
                    onHidePanel: function () {
                        console.log("hide");
                    },
                    onChange: function (n, o) {
                        debugger;
                        $("#divisionId").val(n[0].divisionId);
                        $("#division").val(n[0].divisionName);
                    }
                }
            },
            // ztree组件相关配置
            ztree: {
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "divisionId", // 主键属性名
                        pIdKey: "parentId" // 父节点属性名
                    },
                    key: {
                        name: "divisionName" // 显示名称属性名
                    }
                },
                check: {
                    chkboxType: {
                        'Y': '',
                        'N': ''
                    }
                }
            },
            data: {
                url: getDivisionController() + 'initDivisionZtree',
                type: 'GET',
                success: function () {

                }
            },
            formatter: function (node) {
                node.open = false;
            },
            value: $("#divisionId").val(),
            search: {
                enable: true,
                fields: ["divisionName"]
            }
        });
    }
    // 超级管理员-省市县
    var province = function () {
        var html = "";
        $.ajax({
            url: "/app/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                console.log(data);
                $.each(data, function (idx, item) {
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#belongtoProvince").append(html);
            }
        });
        // 点击省
        $("#belongtoProvince").change(function () {
            let divisionId = $(this).find("option:selected").attr("exid");
            let divisionName = $(this).find("option:selected").attr("value");

            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#belongtoCity option").remove();
            $("#belongtoCity").append(html);
            $("#belongtoArea option").remove();
            $("#belongtoArea").append(html);
            console.log(divisionId);
            console.log(divisionName);
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#belongtoCity").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                // 若是直辖市，直接退出此函数
                return;
            }
            $.ajax({
                url: "/app/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#belongtoCity").append(html);
                }
            });
        });
        // 点击市
        $("#belongtoCity").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#belongtoArea option").remove();
            $("#belongtoArea").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: "/app/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#belongtoArea").append(html);
                }
            });
        });
    }
    // 重置省市县
    var resetProvAndCityAndArea = function(){
        let html = '<option value="" disabled selected style="display:none;">请选择</option>';
        $("#belongtoProvince").val("");
        $("#belongtoCity").html(html);
        $("#belongtoArea").html(html);
    }
    // 初始化搜索栏省市区
    var initProvAndCityAndArea = function () {
        $.ajax({
            url: getServer() + "/fw/taskForm/user/division",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                debugger;
                if (data.message == '超级管理员') {
                    province();
                } else {
                    var html = "<option value='" + data.divisionName + "' exid='" + data.divisionId + "'>" + data.divisionName + "</option>";
                    $("#belongtoProvince").append(html);

                    // 点击省
                    $("#belongtoProvince").change(function () {
                        let divisionId = $(this).find("option:selected").attr("exid");
                        let divisionName = $(this).find("option:selected").attr("value");

                        var html = '<option value="" disabled selected style="display:none;">请选择</option>';
                        $("#belongtoCity option").remove();
                        $("#belongtoCity").append(html);
                        console.log(divisionId);
                        console.log(divisionName);
                        if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                            $("#belongtoCity").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                            // 若是直辖市，直接退出此函数
                            return;
                        }
                        $.ajax({
                            url: "/app/divisions/" + divisionId + "/subdivisions",
                            contentType: "application/json",
                            type: "get",
                            success: function (data) {
                                $.each(data, function (idx, item) {
                                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                });
                                $("#belongtoCity").append(html);
                            }
                        });
                    });
                    // 点击市
                    $("#belongtoCity").change(function () {
                        if ($(this).val() == "") return;
                        var html = '<option value="" disabled selected style="display:none;">请选择</option>';
                        $("#belongtoArea option").remove();
                        $("#belongtoArea").append(html);
                        var divisionId = $(this).find("option:selected").attr("exid");
                        $.ajax({
                            url: "/app/divisions/" + divisionId + "/subdivisions",
                            contentType: "application/json",
                            type: "get",
                            success: function (data) {
                                $.each(data, function (idx, item) {
                                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                });
                                $("#belongtoArea").append(html);
                            }
                        });
                    });

                }
                createTaskGrid();
            }
        });
    }
    return {
        init: init
    };
});

var replayMap;



